package com.ztgf.order.service.pay;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.ztgf.common.constant.Result;
import com.ztgf.common.enums.CodeEnum;
import com.ztgf.common.utils.DateUtils;
import com.ztgf.dubbo.exception.ServiceException;
import com.ztgf.logistics.models.dto.deppon.LogisticsBillDTO;
import com.ztgf.logistics.models.dto.deppon.LogisticsUserDTO;
import com.ztgf.logistics.models.service.deppon.ILogisticsBillService;
import com.ztgf.logistics.models.service.deppon.ILogisticsUserMoneyLogService;
import com.ztgf.logistics.models.service.deppon.ILogisticsUserService;
import com.ztgf.order.common.config.YmlConfig;
import com.ztgf.order.mapper.pay.PayOrderLogMapper;
import com.ztgf.order.models.bo.pay.PayOrderSaveBO;
import com.ztgf.order.models.dto.*;
import com.ztgf.order.models.dto.pay.PayOrderLogDTO;
import com.ztgf.order.models.dto.purchase.PurchaseCommodityBargainDTO;
import com.ztgf.order.models.dto.purchase.PurchaseInfoDTO;
import com.ztgf.order.models.enums.OrderStateEnum;
import com.ztgf.order.models.service.*;
import com.ztgf.order.models.service.async.IAsyncOrderService;
import com.ztgf.order.models.service.pay.IPayOrderService;
import com.ztgf.order.models.service.purchase.IPurchaseCommodityBargainService;
import com.ztgf.order.models.service.purchase.IPurchaseInfoService;
import com.ztgf.order.models.vo.pay.PayOrderVO;
import com.ztgf.pay.models.bo.PayUserMoneySaveBO;
import com.ztgf.pay.models.dto.PayOrderDTO;
import com.ztgf.pay.models.service.IPayUserRechargeService;
import com.ztgf.shopping.models.dto.shop.ShopAnnualFeeDTO;
import com.ztgf.shopping.models.dto.shop.ShopEarnestMoneyDTO;
import com.ztgf.shopping.models.dto.shop.ShopInfoDTO;
import com.ztgf.shopping.models.dto.shop.ShopSysInvoiceDTO;
import com.ztgf.shopping.models.service.shop.IShopAnnualFeeService;
import com.ztgf.shopping.models.service.shop.IShopEarnestMoneyService;
import com.ztgf.shopping.models.service.shop.IShopInfoService;
import com.ztgf.shopping.models.service.shop.IShopSysInvoiceService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.yaml.snakeyaml.events.Event;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * @Description:
 * @Author: mxli
 * @Date: 2021-09-16 16:04
 **/
@Service
@Slf4j
public class PayNotifyServiceImpl implements IPayNotifyService {

    @Resource
    private IOrderPayRelationService orderPayRelationService;
    @Resource
    private IOrderInfoService orderInfoService;
    @Resource
    private IOrderStatusService orderStatusService;
    @Resource
    private IOrderCommodityRelationService orderCommodityRelationService;
    @Resource
    private IOrderExpirationDateService orderExpirationDateService;
    @Resource
    private IOrderDeadlineRecordService orderDeadlineRecordService;
    @Resource
    private IAsyncOrderService asyncOrderService;
    @Resource
    private IPayOrderService payOrderService;
    @Resource
    private IPurchaseCommodityBargainService purchaseCommodityBargainService;
    @Resource
    private IPurchaseInfoService purchaseInfoService;
    @Resource
    private IOrderReturnCommodityService orderReturnCommodityService;
    @Resource
    private PayOrderLogMapper payOrderLogMapper;

    @DubboReference
    private IShopAnnualFeeService shopAnnualFeeService;
    @DubboReference
    private IShopEarnestMoneyService shopEarnestMoneyService;
    @DubboReference
    private IShopInfoService shopInfoService;
    @DubboReference
    private IPayUserRechargeService payUserRechargeService;
    @DubboReference
    private ILogisticsUserService logisticsUserService;
    @DubboReference
    private ILogisticsUserMoneyLogService logisticsUserMoneyLogService;
    @DubboReference
    private ILogisticsBillService logisticsBillService;
    @Resource
    private IOrderPaymentTypeService orderPaymentTypeService;
    @Resource
    private IOrderPaymentScaleService orderPaymentScaleService;
    @Resource
    private IOrderReturnCommodityRefundService orderReturnCommodityRefundService;
    @Resource
    private YmlConfig ymlConfig;
    @DubboReference
    private IShopSysInvoiceService shopSysInvoiceService;

    @Override
    public void saveOrder(PayOrderDTO orderDTO, PayOrderLogDTO logDTO) {
        OrderPayRelationDTO oldOrderPayRelationDTO = orderPayRelationService.selectById(logDTO.getOrderPeriodsId());
        if(oldOrderPayRelationDTO == null){
            log.error("支付回调错误savePaySuccess.OrderPayRelationDTO is null--->>>"  + JSON.toJSONString(orderDTO));
            throw new ServiceException(CodeEnum.FAIL_100002);
        }
        oldOrderPayRelationDTO.setPayType(orderDTO.getType());
        OrderPayRelationDTO dto = new OrderPayRelationDTO();
        dto.setPayState(orderDTO.getStatus());
        dto.setPayType(orderDTO.getType());
        if(orderDTO.getStatus() == 2){
            dto.setPaySuccessTime(DateUtils.getCurrentDateTime());
        }
        //修改订单支付状态
        oldOrderPayRelationDTO.setPayState(orderDTO.getStatus());
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("id", oldOrderPayRelationDTO.getId());
        wrapper.ne("pay_state", 2);
        boolean flag = orderPayRelationService.update(dto, wrapper);
        if(!flag){
            throw new ServiceException(CodeEnum.FAIL_100011);
        }


        Long orderId = logDTO.getOrderId();

        Date currentDateTime = DateUtils.getCurrentDateTime();//当前时间

        OrderInfoDTO orderInfoDTO = orderInfoService.selectById(orderId);
        OrderStatusDTO orderStatusDTO = orderStatusService.getByOrderId(orderId);
        if(orderInfoDTO == null || orderStatusDTO == null){
            log.error("支付回调错误savePaySuccess.orderInfoDTO.orderStatusDTO is null--->>>"  + JSON.toJSONString(orderDTO));
            throw new ServiceException(CodeEnum.FAIL_100002);
        }

        boolean unfreezeMoney = false;//是否解冻金额
        boolean payCommissionMoney = false;//是否支付佣金

        List<OrderCommodityRelationDTO> orderCommodityRelationDTOList = orderCommodityRelationService.getByOrderId(orderId);

        //货物生产状态 0未生成、1生产中、2生产完成
        int goodsProductionState = 0;
        //判断全部支付完成
        boolean paySuccess = orderPayRelationService.getOrderAllPaySuccess(orderId, oldOrderPayRelationDTO.getId());
        boolean sendNotice = false;
        int orderStatus = orderStatusDTO.getOrderState();

        //赊销订单
        OrderPaymentTypeDTO typeDTO = orderPaymentTypeService.getOrderPaymentByOrderIdAndType(orderInfoDTO.getId(), 1,2);
        if(typeDTO != null){
            //解冻金额
            if(oldOrderPayRelationDTO.getPayType() != 2){
                unfreezeMoney = true;
            }

            if(oldOrderPayRelationDTO.getPeriods() == 1){
                //支付佣金
                payCommissionMoney = true;
            }

            //修改赊销支付信息
            wrapper = new EntityWrapper();
            wrapper.eq("pay_relation_id", oldOrderPayRelationDTO.getId());
            wrapper.ne("payment_status", 2);
            OrderPaymentScaleDTO scaleDTO = orderPaymentScaleService.selectOne(wrapper);
            OrderPaymentScaleDTO newScaleDTO = new OrderPaymentScaleDTO();
            newScaleDTO.setPaymentStatus(2);
            newScaleDTO.setPaymentSuccessTime(new Date());
            newScaleDTO.setPaymentType(orderDTO.getType());
            wrapper = new EntityWrapper();
            wrapper.eq("pay_relation_id", oldOrderPayRelationDTO.getId());
            wrapper.eq("payment_status", scaleDTO.getPaymentStatus());
            if(!this.orderPaymentScaleService.update(newScaleDTO, wrapper)){
                throw new ServiceException(CodeEnum.FAIL_100011);
            }
            boolean isRefundPaycommissionMoney = false;
            //修改订单状态 支付完成
            OrderStatusDTO newOrderStatusDTO = new OrderStatusDTO();
            if(paySuccess){
                wrapper = new EntityWrapper();
                //修改赊销状态
                OrderPaymentTypeDTO newTypeDTO = new OrderPaymentTypeDTO();
                if(typeDTO.getReceiveStatus() == 1){

                    //查询所有退款订单
                    wrapper = new EntityWrapper();
                    wrapper.eq("order_id", orderInfoDTO.getId());
                    List<OrderReturnCommodityDTO> returnCommodityDTOList = orderReturnCommodityService.selectList(wrapper);
                    boolean isReturnOrder = true;

                    if(returnCommodityDTOList != null && returnCommodityDTOList.size() > 0){
                        for(OrderReturnCommodityDTO returnCommodityDTO : returnCommodityDTOList){
                            if(returnCommodityDTO.getAfterSalesState() != 3){
                                isReturnOrder = false;
                                break;
                            }
                        }
                    }
                    if(isReturnOrder){
                        newOrderStatusDTO.setOrderState(5);
                        newTypeDTO.setReceiveStatus(2);
                        wrapper.eq("receive_status", typeDTO.getReceiveStatus());
                        isRefundPaycommissionMoney = true;
                    }

                }

                newTypeDTO.setPaymentStatus(1);
                wrapper.eq("id", typeDTO.getId());
                wrapper.eq("payment_status", typeDTO.getPaymentStatus());
                if(!this.orderPaymentTypeService.update(newTypeDTO, wrapper)){
                    throw new ServiceException(CodeEnum.FAIL_100011);
                }
            }

            //修改订单状态
            boolean isUpdateOrderStatus = false;
            wrapper = new EntityWrapper();
            wrapper.eq("order_id", orderId);
            if(newOrderStatusDTO.getOrderState() != null){
                wrapper.eq("order_state", orderStatusDTO.getOrderState());
                isUpdateOrderStatus = true;
                sendNotice = true;
            }

            if(isUpdateOrderStatus){
                if(!orderStatusService.update(newOrderStatusDTO, wrapper)){
                    throw new ServiceException(CodeEnum.FAIL_200022);
                }
            }

            if(isRefundPaycommissionMoney){
                // 订单取消删除订单倒计时
                Wrapper<OrderExpirationDateDTO> a = new EntityWrapper<>();
                a.eq("order_id", orderInfoDTO.getId());
                orderExpirationDateService.delete(a);
                //退款佣金或砍价服务费
                TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
                    @Override
                    public void afterCommit() {
                        try{
                            PayOrderSaveBO payOrderSaveBO = new PayOrderSaveBO();
                            payOrderSaveBO.setType(13);
                            payOrderSaveBO.setIds(orderId.toString());
                            payOrderSaveBO.setPayType(0);
                            asyncOrderService.savePay(payOrderSaveBO, false);
                        } catch (ServiceException e) {
                            log.error("退款佣金或砍价服务费", e);
                        }
                    }
                });

            }
        } else {
            if(oldOrderPayRelationDTO.getPayType() == null){
                oldOrderPayRelationDTO.setPayType(0);
            }
            //是否解冻或者支付佣金
            if(oldOrderPayRelationDTO.getPeriods() == 1){
                //判断是否是赊销支付
                if(orderInfoDTO.getPayType() == 1){ //支付方式 0全款、1分批
                    if(orderStatusDTO.getContactState() == 2 && oldOrderPayRelationDTO.getPayType() != 2){
                        //解冻金额
                        unfreezeMoney = true;
                    }
                    goodsProductionState = 1;
                    //修改备货时间
                    if (orderStatusDTO.getContactState() == OrderStateEnum.ORDER_CONTACT_STATE_SELLER_SIGN.getCode()) {
                        OrderExpirationDateDTO orderExpirationDateDTO = orderExpirationDateService.getByOrderId(orderId);
                        //处理备货过期倒计时
                        Date stockExpireTime = DateUtils.addDay(currentDateTime, orderCommodityRelationDTOList.get(0).getStockDays());//过期时间
                        orderExpirationDateDTO.setExpirationTime(stockExpireTime);
                        orderExpirationDateDTO.setStatus(OrderStateEnum.ORDER_STATE_ENUM_WAIT_PAY.getCode());
                        flag = orderExpirationDateService.updateByOrderId(orderExpirationDateDTO);//更新过期时间
                        if(!flag){
                            throw new ServiceException(CodeEnum.FAIL_100011);
                        }
                        // 记录备货截止时间
                        flag = orderDeadlineRecordService.insert(orderId, 9, stockExpireTime);
                        if(!flag){
                            throw new ServiceException(CodeEnum.FAIL_100011);
                        }
                        log.info("orderid-------" + orderId + "--------备货倒计时5----------");
                    }

                } else {
                    if(orderStatusDTO.getContactState() == 2 && orderInfoDTO.getSellPayType() == 1){// 卖家店铺类型 0 担保交易 1先款交易
                        //解冻金额
                        if(oldOrderPayRelationDTO.getPayType() != 2){
                            unfreezeMoney = true;
                        }

                        //支付佣金
                        payCommissionMoney = true;

                    }
                    goodsProductionState = 2;
                }

                //支付佣金
                if(oldOrderPayRelationDTO.getPayType() == 2) {
                    payCommissionMoney = true;
                }
            } else {
                if(orderInfoDTO.getSellPayType() == 1){// 卖家店铺类型 0 担保交易 1先款交易
                    //解冻金额
                    if(oldOrderPayRelationDTO.getPayType() != 2){
                        unfreezeMoney = true;
                    }
                    //支付佣金
                    if(orderStatusDTO.getCommissionMoneyPayStatus() != 2){
                        payCommissionMoney = true;
                    }

                } else {
                    if(oldOrderPayRelationDTO.getPeriods() == 2 && oldOrderPayRelationDTO.getPayType() == 2 && orderStatusDTO.getCommissionMoneyPayStatus() != 2){
                        //支付佣金
                        payCommissionMoney = true;
                    }
                }

            }

            //修改订单状态 已签合同，待付款或者待钱合同--- 待发货
            if(orderStatusDTO.getContactState() == 2 && (orderStatusDTO.getOrderState() == 1 || orderStatusDTO.getOrderState() == 2) && paySuccess){
                orderStatus = 3;
                //更改订单发货倒计时
                List<Integer> sendList = new ArrayList<Integer>();
                //处理多个商品中获取发货时间为最少的
                for(OrderCommodityRelationDTO orderCommodityRelationDTO : orderCommodityRelationDTOList){
                    sendList.add(orderCommodityRelationDTO.getSendDays());
                }
                Integer sendDaysNum = Collections.max(sendList);
                //更新倒计时
                OrderExpirationDateDTO orderExpirationDateDTO = orderExpirationDateService.getByOrderId(orderId);
                //SysDictDTO sysDictDTO = sysDictService.getByName(OrderExpireTimeConstant.WAIT_DELIVER_GOODS);//卖家签订合同后倒计时

                Date expireTime = DateUtils.addDay(currentDateTime, sendDaysNum);//过期时间

                OrderExpirationDateDTO newExpirationDateDTO = new OrderExpirationDateDTO();
                newExpirationDateDTO.setId(orderExpirationDateDTO.getId());
                newExpirationDateDTO.setExpirationTime(expireTime);
                newExpirationDateDTO.setStatus(OrderStateEnum.ORDER_STATE_ENUM_WAIT_DELIVER_GOODS.getCode());
                wrapper = new EntityWrapper();
                wrapper.eq("id", orderExpirationDateDTO.getId());
                wrapper.eq("status", orderExpirationDateDTO.getStatus());

                String tiem = DateUtils.dateToStr(expireTime);
                log.info("orderid-------"+orderId+"--------待发货倒计时3----------"+tiem+"---------天数-----"+sendDaysNum);

                flag = orderExpirationDateService.update(newExpirationDateDTO, wrapper);//更新倒计时
                if(!flag){
                    throw new ServiceException(CodeEnum.FAIL_100011);
                }
                // 待发货截止时间
                flag =  orderDeadlineRecordService.insert(orderId, 5, expireTime);
                if(!flag){
                    throw new ServiceException(CodeEnum.FAIL_100011);
                }

                sendNotice = true;

            }

            //修改订单支付状态
            OrderStatusDTO newOrderStatusDTO = new OrderStatusDTO();
            newOrderStatusDTO.setOrderId(orderId);
            newOrderStatusDTO.setOrderState(orderStatus);
            newOrderStatusDTO.setUpdateTime(new Date());

            if(goodsProductionState > 0){
                newOrderStatusDTO.setGoodsProductionState(goodsProductionState);
            }
            wrapper = new EntityWrapper();
            wrapper.eq("order_id", orderId);
            wrapper.eq("order_state", orderStatusDTO.getOrderState());
            wrapper.eq("contact_state", orderStatusDTO.getContactState());
            wrapper.eq("goods_production_state", orderStatusDTO.getGoodsProductionState());
            flag = orderStatusService.update(newOrderStatusDTO, wrapper);
            if(!flag){
                throw new ServiceException(CodeEnum.FAIL_100011);
            }

        }

        if(payCommissionMoney){
            //支付佣金
            if(oldOrderPayRelationDTO.getPayType() == 2){
                PayOrderSaveBO payOrderSaveBO = new PayOrderSaveBO();
                payOrderSaveBO.setType(1);
                payOrderSaveBO.setIds(orderId.toString());
                payOrderSaveBO.setPayType(0);
                PayOrderVO payOrderVO = new PayOrderVO();
                payOrderService.savePayCommissionMoney(payOrderSaveBO, payOrderVO, null, null);

            } else {
                TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
                    @Override
                    public void afterCommit() {
                    try{
                        //支付佣金
                        PayOrderSaveBO saveBO = new PayOrderSaveBO();
                        saveBO.setType(1);
                        saveBO.setIds(orderId.toString());
                        saveBO.setPayType(0);
                        asyncOrderService.savePay(saveBO, false);
                    } catch (ServiceException e) {
                        log.error("支付佣金错误", e);
                    }
                    }
                });
            }

        }

        if(unfreezeMoney){
            //解冻金额
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
                @Override
                public void afterCommit() {
                try{
                    BigDecimal freezeMoney = oldOrderPayRelationDTO.getRealPayMoney().subtract(oldOrderPayRelationDTO.getRefundMoney());
                    if(freezeMoney.compareTo(BigDecimal.ZERO) > 0){
                        payOrderService.saveUnfreezeMoney(orderInfoDTO, oldOrderPayRelationDTO, freezeMoney, null, null);
                    }
                } catch (ServiceException e) {
                    log.error("解冻佣金或者", e);
                }
                }
            });

        }

        if(sendNotice){
            Long sendShopId = orderInfoDTO.getSellShopId();
            //发送通知信息
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
                @Override
                public void afterCommit() {
                    asyncOrderService.sendOrderNotice(sendShopId, orderId);
                }
            });
        }
    }

    /**
     * 订单佣金支付
     * @param orderDTO
     * @param logDTO
     */
    @Override
    public void saveOrderCommissionMoney(PayOrderDTO orderDTO, PayOrderLogDTO logDTO) {
        OrderStatusDTO orderStatusDTO = orderStatusService.getByOrderId(logDTO.getOrderId());
        if(orderStatusDTO == null){
            log.error("支付回调错误savePaySuccess.orderInfoDTO.orderStatusDTO is null--->>>"  + JSON.toJSONString(orderDTO));
            throw new ServiceException(CodeEnum.FAIL_100002);
        }

        //修改订单支付状态
        OrderStatusDTO dto = new OrderStatusDTO();
        dto.setCommissionMoneyPayStatus(orderDTO.getStatus());
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("id", orderStatusDTO.getId());
        wrapper.ne("commission_money_pay_status", 2);
        boolean flag = orderStatusService.update(dto, wrapper);
        if(!flag){
            throw new ServiceException(CodeEnum.FAIL_100011);
        }
    }

    /**
     * 年费支付
     * @param orderDTO
     * @param logDTO
     */
    @Override
    public void saveAnnualFee(PayOrderDTO orderDTO, PayOrderLogDTO logDTO) {
        ShopAnnualFeeDTO feeDTO = shopAnnualFeeService.getByShopId(logDTO.getPayShopId());
        ShopAnnualFeeDTO newFeeDTO = new ShopAnnualFeeDTO();
        newFeeDTO.setId(feeDTO.getId());
        newFeeDTO.setStatus(1);
        newFeeDTO.setVacancyAmount(BigDecimal.ZERO);
        newFeeDTO.setPaid(logDTO.getMoney().add(feeDTO.getPaid()));
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("id", feeDTO.getId());
        wrapper.eq("vacancy_amount", feeDTO.getVacancyAmount());
        wrapper.ne("status", 1);
        boolean flag = shopAnnualFeeService.update(newFeeDTO, wrapper);
        if(!flag){
            throw new ServiceException(CodeEnum.FAIL_100011);
        }
    }

    /**
     * 采购申请平台砍价服务费支付
     * @param orderDTO
     * @param logDTO
     */
    @Override
    public void saveOrderPurchaseFeeMoney(PayOrderDTO orderDTO, PayOrderLogDTO logDTO) {
        PurchaseCommodityBargainDTO dto = new PurchaseCommodityBargainDTO();
        dto.setPlatBargainStatus(2);
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("purchase_id", logDTO.getOrderId());
        wrapper.eq("plat_bargain_status", 1);
        purchaseCommodityBargainService.update(dto, wrapper);

        PurchaseInfoDTO purchaseInfoDTO = new PurchaseInfoDTO();
        purchaseInfoDTO.setId(logDTO.getOrderId());
        purchaseInfoDTO.setPurchaseFeeMoneyStatus(orderDTO.getStatus());
        wrapper = new EntityWrapper();
        wrapper.eq("id", purchaseInfoDTO.getId());
        wrapper.ne("purchase_fee_money_status", 2);
        boolean flag = purchaseInfoService.update(purchaseInfoDTO, wrapper);
        if(!flag){
            throw new ServiceException(CodeEnum.FAIL_100011);
        }
    }

    /**
     * 砍价成功手续费支付
     * @param orderDTO
     * @param logDTO
     */
    @Override
    public void saveOrderPurchaseFeeMoneyScalePrice(PayOrderDTO orderDTO, PayOrderLogDTO logDTO) {
        OrderInfoDTO dto = new OrderInfoDTO();
        dto.setId(logDTO.getOrderId());
        dto.setPurchaseFeeMoneyScalePriceStatus(orderDTO.getStatus());
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("id", dto.getId());
        wrapper.ne("purchase_fee_money_scale_price_status", 2);
        boolean flag = orderInfoService.update(dto, wrapper);
        if(!flag){
            throw new ServiceException(CodeEnum.FAIL_100011);
        }

        //修改询价单平台砍价手续费
        List<OrderCommodityRelationDTO> commodityRelationDTOList = orderCommodityRelationService.getByOrderId(logDTO.getOrderId());
        if(commodityRelationDTOList == null || commodityRelationDTOList.size() == 0){
            throw new ServiceException(CodeEnum.FAIL_100011);
        }

        for(OrderCommodityRelationDTO commodityRelationDTO : commodityRelationDTOList){
            if(commodityRelationDTO.getPurchaseFeeMoneyScalePrice().compareTo(BigDecimal.ZERO) >0){
                PurchaseCommodityBargainDTO purchaseCommodityBargainDTO = new PurchaseCommodityBargainDTO();
                purchaseCommodityBargainDTO.setPurchaseFeeMoneyScalePayPrice(commodityRelationDTO.getPurchaseFeeMoneyScalePrice());
                purchaseCommodityBargainDTO.setPurchaseFeeMoneyScalePayPriceStatus(orderDTO.getStatus());
                wrapper = new EntityWrapper();
                wrapper.eq("id", commodityRelationDTO.getPurchaseCommodityBargainId());
                wrapper.ne("purchase_fee_money_scale_pay_price_status", 2);
                flag = purchaseCommodityBargainService.update(purchaseCommodityBargainDTO, wrapper);
                if(!flag){
                    throw new ServiceException(CodeEnum.FAIL_100011);
                }
            }
        }
    }

    /**
     * 订单售后退款
     * @param orderDTO
     * @param logDTO
     */
    @Override
    public void saveOrderRefundMoney(PayOrderDTO orderDTO, PayOrderLogDTO logDTO) {
        OrderReturnCommodityRefundDTO refundDTO = orderReturnCommodityRefundService.selectById(logDTO.getOrderPeriodsId());

        if(refundDTO == null || refundDTO == null){
            log.error("支付回调错误7售后退款退款 OrderReturnCommodityRefundDTO is null--->>>"  + JSON.toJSONString(orderDTO));
            throw new ServiceException(CodeEnum.FAIL_100002);
        }
        OrderReturnCommodityRefundDTO newRefundDTO = new OrderReturnCommodityRefundDTO();
        newRefundDTO.setRefundStatus(2);
        newRefundDTO.setId(refundDTO.getId());
        orderReturnCommodityRefundService.updateById(newRefundDTO);
    }

    /**
     * 扣除店铺保证金
     * @param orderDTO
     * @param logDTO
     */
    @Override
    public void saveDeductMargin(PayOrderDTO orderDTO, PayOrderLogDTO logDTO) {
        ShopEarnestMoneyDTO moneyDTO = shopEarnestMoneyService.getByShopId(logDTO.getPayShopId());
        ShopEarnestMoneyDTO newMoneyDTO = new ShopEarnestMoneyDTO();
        newMoneyDTO.setShopId(logDTO.getPayShopId());
        newMoneyDTO.setVacancyAmount(moneyDTO.getVacancyAmount().add(logDTO.getMoney()));
        BigDecimal allMoney = moneyDTO.getPaid().subtract(logDTO.getMoney());//剩的余额
        newMoneyDTO.setPaid(allMoney);//实缴纳金额
        newMoneyDTO.setPayable(allMoney.add(moneyDTO.getVacancyAmount()));//应缴纳金额
        newMoneyDTO.setBalance(allMoney);//余额

        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("id", moneyDTO.getId());
        wrapper.eq("paid", moneyDTO.getPaid());
        boolean flag = shopEarnestMoneyService.update(newMoneyDTO, wrapper);
        if(!flag) {
            throw new ServiceException(CodeEnum.FAIL_100008);
        }
        ShopInfoDTO newShopInfoDTO = new ShopInfoDTO();
        newShopInfoDTO.setId(logDTO.getPayShopId());
        newShopInfoDTO.setEarnestMoney(allMoney);
        flag = shopInfoService.updateById(newShopInfoDTO);
        if(!flag){
            throw new ServiceException(CodeEnum.FAIL_100008);
        }
    }

    /**
     * 取消订单退款
     * @param orderDTO
     * @param logDTO
     */
    @Override
    public void saveOrderCancelRefundMoney(PayOrderDTO orderDTO, PayOrderLogDTO logDTO) {
//        OrderPayRelationDTO oldOrderPayRelationDTO = orderPayRelationService.getByOrderIdAndPeriods(logDTO.getOrderId(), 1);//一期
        OrderPayRelationDTO oldOrderPayRelationDTO = orderPayRelationService.selectById(logDTO.getOrderPeriodsId());//一期
        log.error("---------取消退款-------------" + JSON.toJSONString(oldOrderPayRelationDTO));
        OrderPayRelationDTO newOrderPayRelationDTO = new OrderPayRelationDTO();
        newOrderPayRelationDTO.setId(oldOrderPayRelationDTO.getId());
        newOrderPayRelationDTO.setRefundMoney(oldOrderPayRelationDTO.getRefundMoney());
        newOrderPayRelationDTO.setRefundMoneyStatus(orderDTO.getStatus());
        newOrderPayRelationDTO.setUnfreezeMoney(oldOrderPayRelationDTO.getRefundMoney());
        newOrderPayRelationDTO.setUnfreezeMoneyStatus(orderDTO.getStatus());
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("id", oldOrderPayRelationDTO.getId());
        wrapper.ne("refund_money_status", 2);
        boolean flag = orderPayRelationService.update(newOrderPayRelationDTO, wrapper);
        log.error("---------取消退款1-------------" + flag);
        if(!flag){
            throw new ServiceException(CodeEnum.FAIL_100011);
        }
    }

    /**
     * 取消退砍价手续费
     * @param orderDTO
     * @param logDTO
     */
    @Override
    public void saveOrderCancelPurchaseFeeMoneyScalePrice(PayOrderDTO orderDTO, PayOrderLogDTO logDTO) {
        log.error("---------取消退砍价手续费1-------------");
        OrderInfoDTO dto = new OrderInfoDTO();
        dto.setId(logDTO.getOrderId());
        dto.setPurchaseFeeMoneyScalePriceBackStatus(orderDTO.getStatus());
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("id", dto.getId());
        wrapper.ne("purchase_fee_money_scale_price_back_status", 2);
        boolean flag = orderInfoService.update(dto, wrapper);
        log.error("---------取消退砍价手续费2-------------" + flag);
        if(!flag){
            throw new ServiceException(CodeEnum.FAIL_100011);
        }
    }

    /**
     * 售后订单砍价服务费
     * @param orderDTO
     * @param logDTO
     */
    @Override
    public void saveOrderRefundPurchaseFeeMoneyScalePrice(PayOrderDTO orderDTO, PayOrderLogDTO logDTO) {
        log.error("---------售后订单砍价服务费1-------------");
        OrderReturnCommodityDTO dto = new OrderReturnCommodityDTO();
        dto.setId(logDTO.getOrderId());
        dto.setPurchaseFeeMoneyScalePriceBackStatus(orderDTO.getStatus());
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("id", dto.getId());
        wrapper.ne("purchase_fee_money_scale_price_back_status", 2);
        boolean flag = orderReturnCommodityService.update(dto, wrapper);
        log.error("---------售后订单砍价服务费2-------------");
        if(!flag){
            throw new ServiceException(CodeEnum.FAIL_100011);
        }
    }

    /**
     * 充值成功回调
     * @param logDTO
     */
    @Override
    public void saveRechargeSuccess(PayOrderLogDTO logDTO) {
        if(logDTO.getType() == 15){
            LogisticsUserDTO userDTO = logisticsUserService.selectById(logDTO.getPayShopId());
            LogisticsUserDTO newUserDTO = new LogisticsUserDTO();
            newUserDTO.setMguaranteeMoney(userDTO.getMguaranteeMoney().add(logDTO.getMoney()));
            if(newUserDTO.getMguaranteeMoney().compareTo(userDTO.getMguaranteeMoneyQuota()) >= 0 && userDTO.getContractStatus() == 1){
                newUserDTO.setType(1);
                //判断是否是临时月结
                LogisticsBillDTO dto = logisticsBillService.getNoPayBill(userDTO.getId());
                if(dto == null){
                    newUserDTO.setStatus(0);
                }
            }
            logisticsUserService.updateMoney(logDTO.getId(), newUserDTO, userDTO, logDTO.getMoney(), 0, logDTO.getCreateUserId(), logDTO.getCreateUserName());
            saveFreezeMoney(logDTO.getPayShopId(), logDTO.getMoney(), "冻结，物流保证金");
        } else {
            ShopEarnestMoneyDTO moneyDTO = shopEarnestMoneyService.getByShopId(logDTO.getPayShopId());
            ShopEarnestMoneyDTO newMoneyDTO = new ShopEarnestMoneyDTO();
            newMoneyDTO.setShopId(logDTO.getPayShopId());
            newMoneyDTO.setVacancyAmount(BigDecimal.ZERO);
            BigDecimal allMoney = logDTO.getMoney().add(moneyDTO.getPaid());
            newMoneyDTO.setPaid(allMoney);//实缴纳金额
            newMoneyDTO.setPayable(allMoney);//实缴纳金额
            newMoneyDTO.setBalance(allMoney);//余额

            Wrapper wrapper = new EntityWrapper();
            wrapper.eq("id", moneyDTO.getId());
            wrapper.eq("vacancy_amount", logDTO.getMoney());
            wrapper.ne("status", 1);
            boolean flag = shopEarnestMoneyService.update(newMoneyDTO, wrapper);
            if(flag) {
                ShopInfoDTO newShopInfoDTO = new ShopInfoDTO();
                newShopInfoDTO.setId(logDTO.getPayShopId());
                newShopInfoDTO.setEarnestMoney(allMoney);
                flag = shopInfoService.updateById(newShopInfoDTO);
                if(!flag){
                    throw new ServiceException(CodeEnum.FAIL_100008);
                }
                saveFreezeMoney(logDTO.getPayShopId(), logDTO.getMoney(), "冻结，物流保证金");
            }
        }
    }

    /**
     * 扣除物流保证金
     * @param orderDTO
     * @param logDTO
     */
    @Override
    public void saveLogisticsDeductMargin(PayOrderDTO orderDTO, PayOrderLogDTO logDTO) {
        LogisticsUserDTO userDTO = logisticsUserService.selectById(logDTO.getPayShopId());
        LogisticsUserDTO newUserDTO = new LogisticsUserDTO();
        newUserDTO.setMguaranteeMoney(userDTO.getMguaranteeMoney().subtract(logDTO.getMoney()));
        logisticsUserService.updateMoney(logDTO.getId(), newUserDTO, userDTO, logDTO.getMoney(), 2, logDTO.getCreateUserId(), logDTO.getCreateUserName());
    }

    /**
     * 支付物流账单
     * @param orderDTO
     * @param logDTO
     */
    @Override
    public void saveLogisticsBill(PayOrderDTO orderDTO, PayOrderLogDTO logDTO) {
        LogisticsBillDTO billDTO = logisticsBillService.selectById(logDTO.getOrderId());
        LogisticsBillDTO newBillDTO = new LogisticsBillDTO();
        newBillDTO.setPayStatus(2);
        Date date = new Date();
        newBillDTO.setPayTime(date);
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("id", billDTO.getId());
        wrapper.ne("pay_status", 2);
        boolean flag = logisticsBillService.update(newBillDTO, wrapper);
        if(!flag) {
            throw new ServiceException(CodeEnum.FAIL_200022);
        }
        LogisticsUserDTO userDTO = logisticsUserService.selectById(logDTO.getPayShopId());
        LogisticsUserDTO newUserDTO = new LogisticsUserDTO();
        if(userDTO.getMguaranteeMoneyQuota().compareTo(userDTO.getMguaranteeMoney()) <= 0){
            newUserDTO.setStatus(0);
        }
        BigDecimal moneyUsed = userDTO.getLogisticsMoneyUsed().subtract(logDTO.getMoney());
        newUserDTO.setLogisticsMoneyUsed(moneyUsed.compareTo(BigDecimal.ZERO) < 0 ? BigDecimal.ZERO : moneyUsed);
        newUserDTO.setLogisticsMoneyUnused(userDTO.getLogisticsMoneyQuota().subtract(newUserDTO.getLogisticsMoneyUsed()));
        newUserDTO.setLogisticsMoneyUsedScale(newUserDTO.getLogisticsMoneyUsed().divide(userDTO.getLogisticsMoneyQuota(), 4, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)));
        logisticsUserService.updateMoney(billDTO.getId(), newUserDTO, userDTO, logDTO.getMoney(), 7, logDTO.getCreateUserId(), logDTO.getCreateUserName());

        //添加发票
        ShopSysInvoiceDTO invoiceDTO = new ShopSysInvoiceDTO();
        invoiceDTO.setId(ymlConfig.getPkId());
        invoiceDTO.setOrderId(billDTO.getId());
        invoiceDTO.setShopId(billDTO.getShopId());
        invoiceDTO.setType(0);
        invoiceDTO.setName("物流服务费");
        invoiceDTO.setPrice(billDTO.getMoney());
        invoiceDTO.setStatus(1);
        invoiceDTO.setDeductTime(date);
        if(!shopSysInvoiceService.insert(invoiceDTO)){
            throw new ServiceException(CodeEnum.FAIL_200041);
        }

    }

    @Override
    public void saveFreezeMoney(Long shopId, BigDecimal money, String usage) {
        List<PayUserMoneySaveBO> paySaveBOlist = new ArrayList<>();
        PayUserMoneySaveBO payUserMoneySaveBO = new PayUserMoneySaveBO();
        payUserMoneySaveBO.setUserId(shopId);
        payUserMoneySaveBO.setMoney(money);
        payUserMoneySaveBO.setUsage(usage);
        paySaveBOlist.add(payUserMoneySaveBO);
        Result result = payUserRechargeService.saveFreezeMoney(paySaveBOlist);
        if(!result.success()){
            throw new ServiceException(result.getCode(), result.getMsg());
        }
    }

    @Override
    public void saveOrderRefundCommissionMoney(PayOrderDTO orderDTO, PayOrderLogDTO logDTO) {
        long orderId = logDTO.getOrderId();
        Long refundOrderId = logDTO.getOrderPeriodsId();
        BigDecimal money = logDTO.getMoney();

        OrderInfoDTO orderInfoDTO = orderInfoService.selectById(orderId);

        if(orderInfoDTO == null){
            log.error("支付回调错误saveOrderRefundCommissionMoney.orderInfoDTO.orderStatusDTO is null--->>>"  + JSON.toJSONString(orderDTO));
            throw new ServiceException(CodeEnum.FAIL_100002);
        }

        OrderInfoDTO newOrderDTO = new OrderInfoDTO();
        newOrderDTO.setRefundCommissionMoney(money.add(orderInfoDTO.getRefundCommissionMoney()));
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("id", orderId);
        wrapper.eq("refund_commission_money", orderInfoDTO.getRefundCommissionMoney());

        if(!orderInfoService.update(newOrderDTO, wrapper)){
            throw new ServiceException(CodeEnum.FAIL_100008);
        }

        OrderReturnCommodityDTO commodityDTO = orderReturnCommodityService.selectById(refundOrderId);
        if(commodityDTO != null){
            OrderReturnCommodityDTO newCommodityDTO = new OrderReturnCommodityDTO();
            newCommodityDTO.setRefundCommissionMoneyStatus(2);
            wrapper = new EntityWrapper();
            wrapper.eq("id", commodityDTO.getId());
            wrapper.eq("refund_commission_money_status", commodityDTO.getRefundCommissionMoneyStatus());
            if(!orderReturnCommodityService.update(newCommodityDTO, wrapper)){
                throw new ServiceException(CodeEnum.FAIL_100008);
            }
        }
    }
}
